package com.juzipi.demo.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * 使用自定义realm加入md5 + salt + hash散列
 */


public class CustomerMD5Realm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权=========================>>>");
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        System.out.println("身份信息："+primaryPrincipal);
        //根据用户信息(用户名)获取当前用户的角色信息，以及权限信息
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();//简单授权信息
        //将数据中查询的角色信息赋值给 权限对象
        simpleAuthorizationInfo.addRole("admin");
        simpleAuthorizationInfo.addRole("user");

        //将数据库中的权限信息赋值给权限对象
        simpleAuthorizationInfo.addStringPermission("user:*:01");
        simpleAuthorizationInfo.addStringPermission("student:*:*");

        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取身份信息
        String principal = (String) authenticationToken.getPrincipal();
        //根据用户名查询数据库
        if ("guest".equals(principal)){
            return new SimpleAuthenticationInfo(
                    //参数一：数据库的用户名
                    "guest",
                    //参数二：数据库md5+salt之后的密码
                    "b682e702a9bbb5b8403d69d618ec15b7",
                    //参数三：注册时的随机盐salt
                    //这里加了 盐 的话，它会自动把密码加上盐去处理
                    ByteSource.Util.bytes("1287641826!*^#!*#*^@!*@%T#adsuygdjahsvdjahsv"),
                    //参数四：realm的名字
                    getName());
        }
        return null;
    }
}
